<template>
  <div class="admin-challenge-edit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑任务' : '创建任务' }}</h2>
      <div class="header-actions">
        <button class="admin-btn" @click="goBack">返回列表</button>
        <button class="admin-btn admin-btn-primary" @click="saveChallenge">保存</button>
      </div>
    </div>
    
    <div class="loading-container" v-if="loading">
      <div class="loading-spinner"></div>
      <p>{{ isEdit ? '正在加载任务详情...' : '准备创建任务...' }}</p>
    </div>
    
    <div class="error-container" v-else-if="error">
      <div class="error-icon">❌</div>
      <h3>出错了</h3>
      <p>{{ error }}</p>
      <button class="admin-btn" @click="goBack">返回列表</button>
    </div>
    
    <div class="edit-form-container" v-else>
      <div class="admin-alert admin-alert-info" v-if="isEdit">
        <p>当前正在编辑ID为 <strong>{{ taskId }}</strong> 的任务。</p>
      </div>
      
      <div class="admin-form edit-form">
        <div class="form-tabs">
          <div 
            class="form-tab" 
            :class="{ active: activeTab === 'basic' }"
            @click="activeTab = 'basic'"
          >
            基本信息
          </div>
          <div 
            class="form-tab" 
            :class="{ active: activeTab === 'rules' }"
            @click="activeTab = 'rules'"
          >
            任务规则
          </div>
          <div 
            class="form-tab" 
            :class="{ active: activeTab === 'rewards' }"
            @click="activeTab = 'rewards'"
          >
            奖励设置
          </div>
        </div>
        
        <!-- 基本信息 -->
        <div class="form-tab-content" v-show="activeTab === 'basic'">
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label required">任务名称</label>
              <input
                type="text"
                v-model="formData.title"
                class="admin-form-input"
                placeholder="请输入任务名称"
              >
              <div class="admin-form-error" v-if="errors.title">{{ errors.title }}</div>
            </div>
          </div>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">任务类型</label>
              <select v-model="formData.category" class="admin-form-input">
                <option value="">请选择类型</option>
                <option value="daily">日常生活</option>
                <option value="energy">节能减排</option>
                <option value="transport">绿色出行</option>
                <option value="recycling">垃圾分类</option>
                <option value="water">节约用水</option>
              </select>
              <div class="admin-form-error" v-if="errors.category">{{ errors.category }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label required">难度级别</label>
              <div class="difficulty-selector">
                <div 
                  v-for="n in 3" 
                  :key="n" 
                  :class="['difficulty-option', formData.difficulty >= n ? 'active' : '']"
                  @click="formData.difficulty = n"
                >
                  {{ n }}
                </div>
              </div>
              <div class="admin-form-error" v-if="errors.difficulty">{{ errors.difficulty }}</div>
            </div>
          </div>
          
          <div class="form-row two-col">
            <div class="admin-form-item">
              <label class="admin-form-label required">开始时间</label>
              <input
                type="date"
                v-model="formData.startTime"
                class="admin-form-input"
              >
              <div class="admin-form-error" v-if="errors.startTime">{{ errors.startTime }}</div>
            </div>
            
            <div class="admin-form-item">
              <label class="admin-form-label required">结束时间</label>
              <input
                type="date"
                v-model="formData.endTime"
                class="admin-form-input"
              >
              <div class="admin-form-error" v-if="errors.endTime">{{ errors.endTime }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label required">任务描述</label>
              <textarea
                v-model="formData.description"
                class="admin-form-input description-input"
                placeholder="请输入任务描述"
                rows="4"
              ></textarea>
              <div class="admin-form-error" v-if="errors.description">{{ errors.description }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">封面图片</label>
              <div class="image-uploader">
                <div class="image-preview" v-if="formData.coverImage">
                  <img :src="formData.coverImage" alt="封面预览">
                  <button class="remove-image-btn" @click="removeCoverImage">×</button>
                </div>
                <div class="upload-placeholder" v-else @click="triggerImageUpload">
                  <div class="upload-icon">+</div>
                  <div class="upload-text">点击上传图片</div>
                </div>
                <input
                  type="file"
                  ref="imageInput"
                  style="display: none"
                  accept="image/*"
                  @change="handleImageUpload"
                >
              </div>
              <div class="admin-form-helper">建议尺寸: 800×400像素，JPG/PNG格式</div>
              <div class="admin-form-error" v-if="errors.coverImage">{{ errors.coverImage }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">状态</label>
              <div class="status-selector">
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="upcoming">
                  <span class="status-label">即将开始</span>
                </label>
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="active">
                  <span class="status-label">进行中</span>
                </label>
                <label class="status-option">
                  <input type="radio" v-model="formData.status" value="completed">
                  <span class="status-label">已结束</span>
                </label>
              </div>
              <div class="admin-form-error" v-if="errors.status">{{ errors.status }}</div>
            </div>
          </div>
        </div>
        
        <!-- 任务规则 -->
        <div class="form-tab-content" v-show="activeTab === 'rules'">
          <div class="rules-header">
            <h3>任务规则列表</h3>
            <button class="admin-btn admin-btn-primary" @click="addRule">
              添加规则
            </button>
          </div>
          
          <div class="empty-rules" v-if="formData.rules.length === 0">
            <div class="empty-icon">📝</div>
            <div class="empty-text">暂无规则，点击"添加规则"按钮创建</div>
          </div>
          
          <div class="rules-list" v-else>
            <div 
              v-for="(rule, index) in formData.rules" 
              :key="index"
              class="rule-item"
            >
              <div class="rule-header">
                <h4>规则 #{{ index + 1 }}</h4>
                <button class="delete-rule-btn" @click="deleteRule(index)">删除</button>
              </div>
              
              <div class="rule-content">
                <div class="form-row">
                  <div class="admin-form-item">
                    <label class="admin-form-label required">规则标题</label>
                    <input
                      type="text"
                      v-model="rule.title"
                      class="admin-form-input"
                      placeholder="例如：每日骑自行车上班"
                    >
                  </div>
                </div>
                
                <div class="form-row two-col">
                  <div class="admin-form-item">
                    <label class="admin-form-label required">规则天数</label>
                    <input
                      type="number"
                      v-model.number="rule.day"
                      class="admin-form-input"
                      min="1"
                    >
                  </div>
                  
                  <div class="admin-form-item">
                    <label class="admin-form-label">积分奖励</label>
                    <input
                      type="number"
                      v-model.number="rule.points"
                      class="admin-form-input"
                      min="0"
                    >
                  </div>
                </div>
                
                <div class="form-row">
                  <div class="admin-form-item">
                    <label class="admin-form-label required">规则描述</label>
                    <textarea
                      v-model="rule.description"
                      class="admin-form-input"
                      placeholder="详细描述该规则的要求..."
                      rows="3"
                    ></textarea>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 奖励设置 -->
        <div class="form-tab-content" v-show="activeTab === 'rewards'">
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label required">积分奖励</label>
              <input
                type="number"
                v-model.number="formData.pointsReward"
                class="admin-form-input"
                min="0"
                placeholder="完成任务后获得的积分数量"
              >
              <div class="admin-form-error" v-if="errors.pointsReward">{{ errors.pointsReward }}</div>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">特殊奖励</label>
              <div class="special-rewards">
                <label class="reward-option">
                  <input type="checkbox" v-model="formData.rewards.badge">
                  <span class="reward-label">徽章奖励</span>
                </label>
                <label class="reward-option">
                  <input type="checkbox" v-model="formData.rewards.certificate">
                  <span class="reward-label">电子证书</span>
                </label>
                <label class="reward-option">
                  <input type="checkbox" v-model="formData.rewards.coupon">
                  <span class="reward-label">优惠券</span>
                </label>
              </div>
            </div>
          </div>
          
          <div class="form-row" v-if="formData.rewards.badge">
            <div class="admin-form-item">
              <label class="admin-form-label">徽章名称</label>
              <input
                type="text"
                v-model="formData.rewards.badgeName"
                class="admin-form-input"
                placeholder="例如：低碳勇士"
              >
            </div>
          </div>
          
          <div class="form-row" v-if="formData.rewards.coupon">
            <div class="admin-form-item">
              <label class="admin-form-label">优惠券详情</label>
              <textarea
                v-model="formData.rewards.couponDetails"
                class="admin-form-input"
                placeholder="描述优惠券的使用条件、有效期等信息..."
                rows="3"
              ></textarea>
            </div>
          </div>
          
          <div class="form-row">
            <div class="admin-form-item">
              <label class="admin-form-label">奖励说明</label>
              <textarea
                v-model="formData.rewardDescription"
                class="admin-form-input"
                placeholder="描述完成任务后获得的奖励详情..."
                rows="4"
              ></textarea>
              <div class="admin-form-error" v-if="errors.rewardDescription">{{ errors.rewardDescription }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="form-actions">
        <button class="admin-btn" @click="goBack">取消</button>
        <button class="admin-btn admin-btn-primary" @click="saveChallenge">保存任务</button>
      </div>
    </div>
  </div>
</template>

<script>
import { getTaskDetail, updateTask } from '@/api/task.js'

export default {
  name: 'AdminTaskEdit',
  data() {
    return {
      taskId: this.$route.params.id,
      isEdit: !!this.$route.params.id,
      loading: false,
      error: null,
      activeTab: 'basic',
      errors: {},
      imageFile: null,
      formData: {
        title: '',
        category: '',
        difficulty: 1,
        startTime: '',
        endTime: '',
        description: '',
        coverImage: '',
        status: 'upcoming',
        pointsReward: 100,
        rewardDescription: '',
        rules: [],
        rewards: {
          badge: false,
          certificate: false,
          coupon: false,
          badgeName: '',
          couponDetails: ''
        }
      }
    }
  },
  created() {
    if (this.isEdit) {
      this.fetchChallengeData()
    } else {
      // 设置默认开始时间为今天
      const today = new Date()
      this.formData.startTime = this.formatDateToISO(today)
      
      // 设置默认结束时间为7天后
      const endDate = new Date()
      endDate.setDate(today.getDate() + 7)
      this.formData.endTime = this.formatDateToISO(endDate)
    }
  },
  methods: {
    fetchChallengeData() {
      this.loading = true
      this.error = null
      
      // 调用API获取数据
      getTaskDetail(Number(this.taskId))
        .then(response => {
          console.log('获取任务详情成功:', response)
          
          // 检查响应
          if (response.code === 200 && response.data) {
            const taskData = response.data
            
            // 转换后端数据为表单格式
            this.formData = {
              title: taskData.taskName || '',
              category: this.mapTypeToCategory(taskData.taskType || ''),
              difficulty: taskData.taskDifficulty || 1,
              startTime: taskData.startTime || '',
              endTime: taskData.endTime || '',
              description: taskData.taskDescription || '',
              coverImage: taskData.coverImage || '',
              status: this.mapStatusToString(taskData.taskStatus),
              pointsReward: taskData.pointReward || 100,
              rewardDescription: taskData.rewardDescription || '',
              rewards: {
                badge: taskData.hasBadge || false,
                certificate: taskData.hasCertificate || false,
                coupon: taskData.hasCoupon || false,
                badgeName: taskData.badgeName || '',
                couponDetails: taskData.couponDetails || ''
              },
              rules: (taskData.taskDTOList || []).map((rule, index) => ({
                id: rule.id,
                title: rule.title || `第${index + 1}天`,
                day: index + 1,
                points: rule.points || 30,
                description: rule.description || ''
              }))
            }
            
            this.loading = false
          } else {
            this.error = '获取任务数据失败'
            this.loading = false
          }
        })
        .catch(error => {
          console.error('获取任务详情失败:', error)
          this.error = `获取任务数据出错: ${error.message || '未知错误'}`
          this.loading = false
        })
    },
    mapTypeToCategory(type) {
      // 根据后端类型转为前端分类
      const typeMap = {
        '低碳生活': 'daily',
        '资源回收': 'recycling',
        '节能减排': 'energy',
        '绿色出行': 'transport',
        '节约用水': 'water'
      }
      
      return typeMap[type] || 'daily'
    },
    mapCategoryToType(category) {
      // 从前端分类转为后端类型
      const categoryMap = {
        'daily': '低碳生活',
        'recycling': '资源回收',
        'energy': '节能减排',
        'transport': '绿色出行',
        'water': '节约用水'
      }
      
      return categoryMap[category] || '低碳生活'
    },
    mapStatusToString(status) {
      // 将数字状态转为字符串状态
      if (typeof status === 'number') {
        switch(status) {
          case 0: return 'upcoming'
          case 1: return 'active'
          case 2: return 'completed'
          default: return 'upcoming'
        }
      }
      return status || 'upcoming'
    },
    mapStringToStatus(str) {
      // 将字符串状态转为数字状态
      const statusMap = {
        'upcoming': 0,
        'active': 1,
        'completed': 2
      }
      
      return statusMap[str] !== undefined ? statusMap[str] : 0
    },
    triggerImageUpload() {
      this.$refs.imageInput.click()
    },
    handleImageUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件类型
      if (!file.type.match('image.*')) {
        this.errors.coverImage = '请上传图片文件（JPG, PNG等）'
        return
      }
      
      // 检查文件大小
      if (file.size > 5 * 1024 * 1024) { // 5MB
        this.errors.coverImage = '图片大小不能超过5MB'
        return
      }
      
      // 创建临时URL用于预览
      this.formData.coverImage = URL.createObjectURL(file)
      this.errors.coverImage = null
    },
    removeCoverImage() {
      this.formData.coverImage = ''
      this.$refs.imageInput.value = null
    },
    addRule() {
      this.formData.rules.push({
        title: '',
        day: this.formData.rules.length + 1,
        points: 30,
        description: ''
      })
    },
    deleteRule(index) {
      if (confirm('确定要删除此规则吗？')) {
        this.formData.rules.splice(index, 1)
        
        // 更新规则天数
        this.formData.rules.forEach((rule, i) => {
          rule.day = i + 1
        })
      }
    },
    validate() {
      this.errors = {}
      
      // 基本信息验证
      if (!this.formData.title) {
        this.errors.title = '请输入任务名称'
      }
      
      if (!this.formData.category) {
        this.errors.category = '请选择任务类型'
      }
      
      if (!this.formData.difficulty) {
        this.errors.difficulty = '请选择难度级别'
      }
      
      if (!this.formData.startTime) {
        this.errors.startTime = '请选择开始时间'
      }
      
      if (!this.formData.endTime) {
        this.errors.endTime = '请选择结束时间'
      } else if (this.formData.startTime && new Date(this.formData.endTime) <= new Date(this.formData.startTime)) {
        this.errors.endTime = '结束时间必须晚于开始时间'
      }
      
      if (!this.formData.description) {
        this.errors.description = '请输入任务描述'
      }
      
      // 奖励验证
      if (typeof this.formData.pointsReward !== 'number' || this.formData.pointsReward < 0) {
        this.errors.pointsReward = '积分奖励必须是大于等于0的数字'
      }
      
      return Object.keys(this.errors).length === 0
    },
    goBack() {
      this.$router.push('/admin/challenges')
    },
    saveChallenge() {
      if (!this.validate()) {
        this.activeTab = 'basic' // 切换到基本信息页面显示错误
        return
      }
      
      this.loading = true
      
      // 将表单数据转换为API格式
      const taskDTO = {
        id: this.isEdit ? Number(this.taskId) : undefined,
        taskName: this.formData.title,
        taskType: this.mapCategoryToType(this.formData.category),
        taskDifficulty: this.formData.difficulty,
        startTime: this.formData.startTime,
        endTime: this.formData.endTime,
        taskDescription: this.formData.description,
        coverImage: this.formData.coverImage,
        taskStatus: this.mapStringToStatus(this.formData.status),
        pointReward: this.formData.pointsReward,
        rewardDescription: this.formData.rewardDescription,
        hasBadge: this.formData.rewards.badge,
        hasCertificate: this.formData.rewards.certificate,
        hasCoupon: this.formData.rewards.coupon,
        badgeName: this.formData.rewards.badgeName,
        couponDetails: this.formData.rewards.couponDetails,
        // 转换规则列表
        taskDTOList: this.formData.rules.map(rule => ({
          id: rule.id,
          title: rule.title,
          day: rule.day,
          points: rule.points,
          description: rule.description
        }))
      }
      
      console.log('准备保存任务数据:', taskDTO)
      
      // 根据是编辑还是新建，调用不同API
      if (this.isEdit) {
        updateTask(taskDTO)
          .then(response => {
            console.log('更新任务成功:', response)
            alert('任务更新成功！')
            this.loading = false
            this.goBack()
          })
          .catch(error => {
            console.error('更新任务失败:', error)
            alert(`更新任务失败: ${error.message || '未知错误'}`)
            this.loading = false
          })
      } else {
        // 如果是新建，我们需要添加创建任务的API（现在还没有添加）
        // 暂时还是使用模拟方式
        console.warn('创建任务API尚未添加，使用模拟方式')
        setTimeout(() => {
          alert('任务创建成功！')
          this.loading = false
          this.goBack()
        }, 1000)
      }
    },
    // 日期格式化方法
    formatDateToISO(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.admin-challenge-edit {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ff4d4f;
}

.edit-form-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.form-tab {
  padding: 12px 16px;
  cursor: pointer;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.65);
  position: relative;
  transition: all 0.3s;
}

.form-tab:hover {
  color: #1890ff;
}

.form-tab.active {
  color: #1890ff;
}

.form-tab.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #1890ff;
}

.form-tab-content {
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.form-row {
  margin-bottom: 24px;
}

.form-row.two-col {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.admin-form-label.required::after {
  content: '*';
  color: #ff4d4f;
  margin-left: 4px;
}

.description-input {
  resize: vertical;
}

.admin-form-helper {
  margin-top: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.difficulty-selector {
  display: flex;
  gap: 16px;
}

.difficulty-option {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.difficulty-option:hover {
  background-color: #e6f7ff;
}

.difficulty-option.active {
  background-color: #1890ff;
  color: white;
}

.status-selector {
  display: flex;
  gap: 24px;
}

.status-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.status-option input {
  margin-right: 8px;
}

.image-uploader {
  width: 100%;
  margin-bottom: 8px;
}

.image-preview {
  width: 200px;
  height: 100px;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
}

.upload-placeholder {
  width: 200px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-placeholder:hover {
  border-color: #1890ff;
}

.upload-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.45);
}

.upload-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.rules-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.rules-header h3 {
  margin: 0;
}

.rules-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.rule-item {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.rule-header h4 {
  margin: 0;
}

.delete-rule-btn {
  border: none;
  background: none;
  color: #ff4d4f;
  cursor: pointer;
  font-size: 14px;
}

.rule-content {
  padding: 16px;
}

.empty-rules {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  background-color: #fafafa;
  border-radius: 4px;
  border: 1px dashed #d9d9d9;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 16px;
  color: rgba(0, 0, 0, 0.25);
}

.empty-text {
  color: rgba(0, 0, 0, 0.45);
}

.special-rewards {
  display: flex;
  gap: 24px;
}

.reward-option {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.reward-option input {
  margin-right: 8px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  margin-top: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .form-row.two-col {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .header-actions {
    flex-direction: column;
  }
  
  .form-tabs {
    flex-wrap: wrap;
  }
}
</style> 